let grid = Array.from({length: 4}, () => Array(4).fill(0));
let score = 0;

// 初始化游戏格子，随机生成两个初始数字
function initGame() {
    for (let i = 0; i < 2; i++) {
        addRandomNumber();
    }
    updateView();
}

// 随机生成2或4并加入到空位中
function addRandomNumber() {
    let emptyCells = [];
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            if (grid[i][j] === 0) {
                emptyCells.push([i, j]);
            }
        }
    }
    if (emptyCells.length > 0) {
        let [i, j] = emptyCells[Math.floor(Math.random() * emptyCells.length)];
        grid[i][j] = Math.random() < 0.9 ? 2 : 4;
    }
}

// 更新页面上每个单元格的数字显示
function updateView() {
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            let cell = document.getElementById(`cell_${i}_${j}`);
            cell.innerText = grid[i][j] !== 0 ? grid[i][j] : '';
        }
    }
    document.getElementById('score').innerText = score;
}
function moveLeft() {
    grid = grid.map(row => slideAndMerge(row));
}
function moveRight() {
    grid = grid.map(row => {
        let reversedRow = row.slice().reverse(); // 先复制并反转行
        let mergedRow = slideAndMerge(reversedRow); // 对反转后的行进行滑动和合并
        return mergedRow.reverse(); // 合并后再次反转回原来的方向
    });
}
function moveUp() {
    // 转置grid，使其变为列优先，然后对每一列（现为行）应用slideAndMerge，然后再转置回去
    const transposedGrid = grid[0].map((_, colIndex) => grid.map(row => row[colIndex]));
    const movedTransposedGrid = transposedGrid.map(row => slideAndMerge(row));
    grid = movedTransposedGrid[0].map((_, rowIndex) => movedTransposedGrid.map(col => col[rowIndex]));
}
function moveDown() {
    // 转置grid，处理列（现为行），反转每一列（合并后），再转置回去
    const transposedGrid = grid[0].map((_, colIndex) => grid.map(row => row[colIndex]));
    const reversedTransposedGrid = transposedGrid.map(row => row.reverse());
    const movedReversedTransposedGrid = reversedTransposedGrid.map(row => slideAndMerge(row));
    const finalReversedGrid = movedReversedTransposedGrid.map(row => row.reverse());
    grid = finalReversedGrid[0].map((_, rowIndex) => finalReversedGrid.map(col => col[rowIndex]));
}

// 合并并滑动函数
function slideAndMerge(row) {
    row = row.filter(num => num !== 0).concat(Array(4 - row.filter(Boolean).length).fill(0));
    for (let i = 0; i < 3; i++) {
        if (row[i] === row[i + 1]) {
            row[i] *= 2;
            row[i + 1] = 0;
            score += row[i];
        }
    }
    return row.filter(num => num !== 0).concat(Array(4 - row.filter(Boolean).length).fill(0));
}

// 检查是否还能移动
function canMove() {
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            if (grid[i][j] === 0) return true;
            if (i < 3 && grid[i][j] === grid[i + 1][j]) return true;
            if (j < 3 && grid[i][j] === grid[i][j + 1]) return true;
        }
    }
    return false;
}
function checkWin() {
    for (let row of grid) {
        for (let num of row) {
            if (num >= 2048) {
                alert("恭喜！你赢得了游戏！");
                return true;
            }
        }
    }
    return false;
}